/*
 * SessionBean.java
 * Created on 16 juil. 2008, 10:32:36
 * @author Rivo
 */
package gla.centralhotel.uiweb;

import com.sun.rave.web.ui.appbase.AbstractSessionBean;
import gla.centralhotel.business.IBookingManagement;
import gla.centralhotel.business.IHotelAndRoomManagement;
import gla.centralhotel.business.interfaces.IResourceBrowser;
import gla.centralhotel.exception.CollectionRetrieverException;
import gla.centralhotel.model.Agency;
import gla.centralhotel.model.Customer;
import gla.centralhotel.model.Hotel;
import gla.centralhotel.model.Manager;
import gla.centralhotel.model.Price;
import gla.centralhotel.model.Room;
import gla.centralhotel.model.RoomBooking;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.faces.FacesException;

/**
 * <p>Session scope data bean for your application.  Create properties
 *  here to represent cached data that should be made available across
 *  multiple HTTP requests for an individual user.</p>
 *
 * <p>An instance of this class will be created for you automatically,
 * the first time your application evaluates a value binding expression
 * or method binding expression that references a managed bean using
 * this class.</p>
 *
 */
public class SessionBean extends AbstractSessionBean {
    @EJB
    private IHotelAndRoomManagement hotelAndRoomManagement;
    @EJB
    private IBookingManagement bookingManagement;

    @EJB
    private IResourceBrowser resourceBrowser;
    /* Pour la page HotelList */
    private Hotel[] hotelList;
    // Propriété utilisée pour stocker l'objet courant édité et/ou utilisé par une page
    private Manager currentManager;
    private Agency currentAgency;
    private Hotel currentHotel;
    /**
     * currentRoomBooking => Contient refRoom, refCustomer, refAgency
     */
    private RoomBooking currentRoomBooking;
    private Customer currentCustomer;
    private Room currentRoom;
    private Price currentPrice; // A supprimer si ce n'est pas indispensable

    private Room[] roomsByHotel;
    private Price[] pricePerRoom;
    
    private RoomBooking[] roomBookingByHotel;
    
    private Integer userLogged;
    
//    private Integer selectedZipcode;
//    private Integer selectedVille;

//    public Integer getSelectedVille()
//    {
//        return selectedVille;
//    }
//
//    public void setSelectedVille(Integer selectedVille)
//    {
//        this.selectedVille = selectedVille;
//    }
//
//    public Integer getSelectedZipcode()
//    {
//        return selectedZipcode;
//    }
//
//    public void setSelectedZipcode(Integer selectedZipcode)
//    {
//        this.selectedZipcode = selectedZipcode;
//    }

    
    
    public Integer getUserLogged() {
        return userLogged;
    }

    public void setUserLogged(Integer userLogged) {
        this.userLogged = userLogged;
    }

    /* Properties calculées */
    /**
     * Propertie calculée
     * Dépend de l'objet currentRoom du sessionbean
     * @return
     */
    public Price[] getRoomPricesList() {
//        return (Price[]) this.currentRoom.getPriceCollection().toArray();
        //return roomList;
        return null;
    }

    /**
     * Propertie calculée
     * Dépend de l'objet currentRoom du sessionbean
     * @param roomPricesList
     */
    public void setRoomPricesList(Price[] roomPricesList) {
        //this.roomList = roomList;
        ArrayList<Price> l = new ArrayList();
        for (int i = 0; i < roomPricesList.length; i++) {
            l.add(roomPricesList[i]);
        }
//        this.currentRoom.setPriceCollection(l);
    }

    /**
     * Propertie calculée
     * Dépend de l'objet currentHotel du sessionbean
     * @return
     */
    public Room[] getRoomList() {
//        return (Room[]) this.currentHotel.getRoomCollection().toArray();
        //return roomList;
        return null;
    }

    /**
     * Propertie calculée
     * Dépend de l'objet currentHotel du sessionbean
     * @param roomList
     */
    public void setRoomList(Room[] roomList) {
        //this.roomList = roomList;
        ArrayList<Room> l = new ArrayList();
        for (int i = 0; i < roomList.length; i++) {
            l.add(roomList[i]);
        }
//        this.currentHotel.setRoomCollection(l);
    }
    /* Fin des properties calculées */

    public Room getCurrentRoom() {
        return currentRoom;
    }

    public void setCurrentRoom(Room currentRoom) {
        this.currentRoom = currentRoom;
    }

    public RoomBooking[] getRoomBookingByHotel()
    {
        return roomBookingByHotel;
    }

    public void setRoomBookingByHotel(RoomBooking[] roomBookingByHotel)
    {
        this.roomBookingByHotel = roomBookingByHotel;
    }

    public Room[] getRoomsByHotel()
    {
        return roomsByHotel;
    }

    public void setRoomsByHotel(Room[] roomsByHotel)
    {
        this.roomsByHotel = roomsByHotel;
    } 
    
//    public String getCity()
//    {
//        return city;
//    }
//
//    public void setCity(String city)
//    {
//        this.city = city;
//    }
    // <editor-fold defaultstate="collapsed" desc="Managed Component Definition">
    /**
     * <p>Automatically managed component initialization.  <strong>WARNING:</strong>
     * This method is automatically generated, so any user-specified code inserted
     * here is subject to being replaced.</p>
     */
    private void _init() throws Exception {
    }
    // </editor-fold>

    /**
     * <p>Construct a new session data bean instance.</p>
     */
    public SessionBean() {
    }

    /**
     * <p>This method is called when this bean is initially added to
     * session scope.  Typically, this occurs as a result of evaluating
     * a value binding or method binding expression, which utilizes the
     * managed bean facility to instantiate this bean and store it into
     * session scope.</p>
     * 
     * <p>You may customize this method to initialize and cache data values
     * or resources that are required for the lifetime of a particular
     * user session.</p>
     */
    @Override
    public void init() {
        // Perform initializations inherited from our superclass
        super.init();
        // Perform application initialization that must complete
        // *before* managed components are initialized
        // TODO - add your own initialiation code here

        // <editor-fold defaultstate="collapsed" desc="Managed Component Initialization">
        // Initialize automatically managed components
        // *Note* - this logic should NOT be modified
        try {
            _init();
        } catch (Exception e) {
            log("SessionBean1 Initialization Failure", e);
            throw e instanceof FacesException ? (FacesException) e : new FacesException(e);
        }

    // </editor-fold>
    // Perform application initialization that must complete
    // *after* managed components are initialized
    // TODO - add your own initialization code here
        
        
    }

    /**
     * <p>This method is called when the session containing it is about to be
     * passivated.  Typically, this occurs in a distributed servlet container
     * when the session is about to be transferred to a different
     * container instance, after which the <code>activate()</code> method
     * will be called to indicate that the transfer is complete.</p>
     * 
     * <p>You may customize this method to release references to session data
     * or resources that can not be serialized with the session itself.</p>
     */
    @Override
    public void passivate() {
    }

    /**
     * <p>This method is called when the session containing it was
     * reactivated.</p>
     * 
     * <p>You may customize this method to reacquire references to session
     * data or resources that could not be serialized with the
     * session itself.</p>
     */
    @Override
    public void activate() {
    }

    /**
     * <p>This method is called when this bean is removed from
     * session scope.  Typically, this occurs as a result of
     * the session timing out or being terminated by the application.</p>
     * 
     * <p>You may customize this method to clean up resources allocated
     * during the execution of the <code>init()</code> method, or
     * at any later time during the lifetime of the application.</p>
     */
    @Override
    public void destroy() {
    }
    
    public void initializeManagerLoggedHotels(){
        try {
            ArrayList<Hotel> hotels = resourceBrowser.getAllHotelByManager(currentManager);
            Hotel[] tmp = new Hotel[hotels.size()];
            for(int i = 0; i<hotels.size(); i++){
                tmp[i] = hotels.get(i);
            }
            setHotelList(tmp);
        } catch (CollectionRetrieverException ex) {
            Logger.getLogger(SessionBean.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Méthode destinée à être appeler par chaque page qui en a besoin
     * en prenant la current Hotel comme paramètre
     */
    public void intializeRoomListPerHotel() {
        if (currentHotel != null) {
            try {
                ArrayList<Room> rooms = resourceBrowser.getAllRoomByHotel(currentHotel);
                Room[] tmp = new Room[rooms.size()];
                for(int i = 0; i<rooms.size(); i++){
                    tmp[i] = rooms.get(i);
                }
                setRoomByHotel(tmp);
            } catch (CollectionRetrieverException ex) {
                Logger.getLogger(SessionBean.class.getName()).log(Level.SEVERE, 
                        "ECHEC de chargement des chambres par hotel !", ex);
            }
        }

    }

    /**
     * Méthode destinée à être appeler par chaque page qui en a besoin
     * en prenant la current Room comme paramètre
     */
    public void initializePriceListPerRoom() {
        if(currentRoom != null){
            try{
                ArrayList<Price> prices = resourceBrowser.getAllPriceByRoom(currentRoom);
                Price[] tmp = new Price[prices.size()];
                for(int i = 0; i<prices.size(); i++){
                    tmp[i] = prices.get(i);
                }
                setPricePerRoom(tmp);
            }catch(CollectionRetrieverException ex){
                Logger.getLogger(SessionBean.class.getName()).log(Level.SEVERE, 
                        "ECHEC chargement des prix par chambre", ex);
            }
        }
    }

    /**
     * <p>Return a reference to the scoped data bean.</p>
     *
     * @return reference to the scoped data bean
     */
    protected ApplicationBean getApplicationBean() {
        return (ApplicationBean) getBean("ApplicationBean");
    }

    public Hotel[] getHotelList() {
        return hotelList;
    }

    public void setHotelList(Hotel[] hotelList) {
        this.hotelList = hotelList;
    }

    public Hotel getCurrentHotel() {

        return currentHotel;
    }

    public void setCurrentHotel(Hotel currentHotel) {
        this.currentHotel = currentHotel;
    //this.roomList = (Room[]) currentHotel.getRoomCollection().toArray();
    }

    public Manager getCurrentManager() {
        return currentManager;
    }

    public void setCurrentManager(Manager currentManager) {
        this.currentManager = currentManager;
    }

    public Price getCurrentPrice() {
        return currentPrice;
    }

    public void setCurrentPrice(Price currentPrice) {
        this.currentPrice = currentPrice;
    }

    public RoomBooking getCurrentRoomBooking() {
        return currentRoomBooking;
    }

    public void setCurrentRoomBooking(RoomBooking currentRoomBooking) {
        this.currentRoomBooking = currentRoomBooking;
    }

    public Customer getCurrentCustomer() {
        return currentCustomer;
    }

    public void setCurrentCustomer(Customer currentCustomer) {
        this.currentCustomer = currentCustomer;
    }

    public Price[] getPricePerRoom() {
        return pricePerRoom;
    }

    public void setPricePerRoom(Price[] pricePerRoom) {
        this.pricePerRoom = pricePerRoom;
    }

    public Room[] getRoomByHotel() {
        return roomsByHotel;
    }

    public void setRoomByHotel(Room[] roomByHotel) {
        this.roomsByHotel = roomByHotel;
    }

    public Agency getCurrentAgency() {
        return currentAgency;
    }

    public void setCurrentAgency(Agency currentAgency) {
        this.currentAgency = currentAgency;
    }
    
    /**
     * charge une liste de réservation dans le session bean
     * @param hotelId
     * @return
     */
    public void loadRoomBookingListByHotelId( Integer hotelId )
    {
        //RoomBooking[] rbl = new RoomBooking[1];
        //return rbl;
        
        //charge les données
        ArrayList<RoomBooking> alrb = this.bookingManagement.getRoomBookingByHotel(hotelId);
        
        this.roomBookingByHotel = new RoomBooking[alrb.size()];
        for (int i = 0; i < alrb.size(); i++)
        {
            RoomBooking rb = alrb.get(i);
            this.roomBookingByHotel[i] = rb;
        }
        
        //charge les attribut transiant
        this.roomBookingByHotel = this.bookingManagement.setTransientAttr(roomBookingByHotel);
    }
 
    /**
     * filtre la liste des hotel par ville
     * @param zipcodeId
     */
    public void loadHotelListByZipcode( Integer zipcodeId )
    {
        ArrayList<Hotel> ah = this.hotelAndRoomManagement.getHotelListByZipcode(zipcodeId);
        this.hotelList = new Hotel[ah.size()];

        for (int i = 0; i < ah.size(); i++)
        {
            Hotel hotel = ah.get(i);
            hotelList[i]=hotel;
        }
    }
    
    /**
     * charge tous les hotel de la base
     */
    public void loadHotelList()
    {
       
        ArrayList<Hotel> ah = this.hotelAndRoomManagement.getHotelList();
        this.hotelList = new Hotel[ah.size()];
       
        for (int i = 0; i < ah.size(); i++)
        {
            Hotel hotel = ah.get(i);
            hotelList[i]=hotel;
        }
       
    }
}
